/**
 * 
 */
package net.mikoo.seals.manage.web.controller;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.biz.manager.SmsManager;
import net.mikoo.seals.common.WebContext;
import net.mikoo.seals.common.exception.ParametersException;
import net.mikoo.seals.common.exception.SendSmsException;
import net.mikoo.seals.manage.web.common.BaseController;
import net.mikoo.seals.model.Party;
import net.mikoo.seals.utils.DateUtil;
import net.mikoo.seals.utils.StringUtil;
import net.mikoo.seals.utils.ValidatorUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/sms")
public class SmsController extends BaseController {

	Logger logger = Logger.getLogger(SmsController.class);
	
	private static final String SMS_SEND_DATETIME = "sms_send_datetime_";
	

	@Autowired
	private SmsManager smsManager;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	

	@RequestMapping("/send")
	@ResponseBody
	public Map<String, Object> send(String mobile, HttpServletRequest request) {

		try {
			
			
			Party party = this.getParty(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			if(party == null) {
				throw new ParametersException("您还未登陆不允许发送短信");
			}
			
			// 验证手机号码格式是否正确
			if (!ValidatorUtil.isMobile(mobile)) {
				throw new ParametersException("手机号码输入有误");
			}

			String sendTime = redisTemplate.opsForValue().get(SMS_SEND_DATETIME.concat(mobile));
			if(StringUtils.isNotBlank(sendTime)) {
				Date sendDatetime = DateUtil.stringToDate(sendTime.toString(), "yyyy-MM-dd HH:mm:ss");
				Date currentDatetime = DateUtil.getCurretDate();
				sendDatetime = DateUtil.addMinute(sendDatetime, 1);
				if (DateUtil.compare(sendDatetime, currentDatetime) > 0) {
					throw new ParametersException("您操作太频繁，请稍微再试");
				}
				
			}
			

			//生成短信随机码
			String smscode = StringUtil.getRandNum(6);
			System.out.println(smscode);
			JSONObject data = new JSONObject();
			data.put("code", smscode);
			
			try {
				smsManager.sendSms(mobile, "SMS_147435007", data.toString());
				
				redisTemplate.opsForValue().set(SMS_SEND_DATETIME.concat(mobile),DateUtil.formate(new Date(), "yyyy-MM-dd HH:mm:ss"));
				redisTemplate.opsForValue().set("sms_send_code_".concat(mobile), smscode);
			}catch (SendSmsException e) {
				throw new ParametersException("短信发送失败");
			}
			

			return result(SUCCESS, MSG_SUCCESS, data);

		} catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		} catch (Exception e) {
			logger.error("",e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}

	}

}